<?php
//last updated 15.04.09
class CmsCore
{
	var $mMap; //������ � ����������� � ���������, �������� � ���� �� ������� ��������. ������ ������������ � "������� �������".
	var $mRU; //$_SERVER['REQUEST_URI']
	var $mCurrentPageId; //ID ������� ��������
	var $mCurrentPageFile;
	var $mPageTitle; //��������� ��������. ���������� "������� ������"
	var $mPageUrl;
	var $mPageTemplate; //������ ��������. ��, ��� ������ �������� .dwt-���
	var $mBuiltPage; //��������� ������� ��� ����� ��������.
	var $mTitleTagValue; // <title>$mTitleTag</title>
	var $addToDefaultTitle;
	var $requestInfo;
	var $keyWords;
	var $formCaptcha;

	function CmsCore()
	{
		$this->mRU=$_SERVER['REQUEST_URI'];
		$this->keyWords=array('html','txt','noimage','nostyle','aspx','source');
		$this->ParseURI($this->mRU);
		$params = $this->requestInfo["params"];
		$newGet = array();
		for ($i = 0; $i < count($params); $i += 2)
		{
			$newGet[$params[$i]] = $params[$i+1];
		}
		if ($newGet)
		{
			$_GET = array_merge($_GET, $newGet);
		}

	}


	function &Instance()
	{
		static $_instance;
		if(!isset($_instance))
		{
			$_instance = new CmsCore();

		}
		return $_instance;
	}

	function &Get()
	{
		return CmsCore::Instance();
	}


	function ParseURI($request)
	{
		$count = strlen($request);

		$value = null;
		$keywords = false;

		for ($i=0; $i<$count; $i++)
		{
			switch($request[$i])
			{
				case "/":
					{
						if (!is_null($value))
						{
							$this->requestInfo["pages"][] = $value;
						}
						$value = "";
						break;
					}

				case "?":
					{
						return null;
					}

				case ".":
					{
						if (!is_null($value))
						{
							$this->requestInfo["params"][] = $value;
						}
						$value = null;
						break;
					}

				default:
					{
						$value .= $request[$i];
						break;
					}
			}
		}

		if (in_array($value,$this->keyWords))
		{
			$this->requestInfo["words"][] = $value;
		}
		else
		{	if ($value)
		$this->requestInfo["pages"][] = $value;
		}

	}


	function CheckPage($name = "", $parentPageId = 0)
	{
		$this->mPageUrl = '/';
		$requestedPath=$this->requestInfo['pages'];
		if (!$requestedPath[0])
		{
			$requestedPath[0]='index';
		}
		switch ($requestedPath[0])
		{
			case 'corequery': $this->handleCoreQuery(); break;

			case 'coreGetText':
				if (is_numeric($_GET['txtId']))
				{
					header("Content-Type: text/html; charset=windows-1251");
					$table = new CARXTable('cms__textarea',"id={$_GET['txtId']}");
					$data = $table->FetchRow();
					echo "{$data['text']}";
				}
				exit;break;
			case 'execplugin':
				$funcParams=array();
				$plugFunc=$_REQUEST['plugFunc'];
				if (trim($_REQUEST['funcParams']))
				{
					$funcParams=explode("@@",$_REQUEST['funcParams']);
				}
				if ($_REQUEST['plg'])
				{
					header("Content-Type: text/html; charset=windows-1251");
					$plugin='cmsplg__'.$_REQUEST['plg'].'.lib.php';
					$plugClass="cmsplg__{$_REQUEST['plg']}";
					if (file_exists(CMS_PLUGIN_DIR.'/'.$plugin))
					{
						require_once(CMS_PLUGIN_DIR."/".$plugin);
						$plugObject = new $plugClass;
						if (is_numeric($_REQUEST['useProperties']))
						{
							if ($_REQUEST['plgblock'])
							{
								$extraCondition="AND editable_region='".addslashes($_REQUEST['plgblock'])."'";
							}
							$table = new CARXTable("cms_plugin2page","page_id={$_REQUEST['useProperties']} and plugin='$plugClass' $extraCondition",'pluginProperties');
							$props = $table->FetchRow();
							$plugObject->InitConfig($props['pluginProperties']);
						}

						if (!is_callable(array($plugObject,$plugFunc)))
						{
							$plugOutput = $plugObject->getOutput();
						}
						else
						{
							$plugOutput=call_user_func_array(array($plugObject,$plugFunc),$funcParams);
						}
						echo "$plugOutput";
					}
					else
					{
						echo 'Requested plugin does not exist!';
					}

				}
				elseif ($_REQUEST['myadmin'])
				{
					if ($_SESSION['cms_user'])
					{
					require_once($_SERVER['DOCUMENT_ROOT'].'/cms/classes/myadmin.class.php');
					$myadmin = new CARXCMSPlugMyAdmin();
					$myadmin->table= new CARXTable();
					$plugOutput=call_user_func_array(array($myadmin,$plugFunc),$funcParams);
					if ($_REQUEST['json']) $plugOutput=fetcharray_to_simple_json($plugOutput);
					print_r ($plugOutput);
					}

				}
				exit; break;

			case 'execFormHandle':
				header("Content-Type: text/html; charset=windows-1251");
				$checkFormData = checkForms($_POST['plgId'],$_POST['fldValues'],1);
				if ($checkFormData[0]==1)
				{
					if (trim($checkFormData[3]))
					{
						execPluginMethod($_POST['plgId'],$checkFormData[3],1,array($checkFormData[1],$checkFormData[2]));
					}

					echo '1';
				}



				exit; break;

			case 'checkAjaxSupport':
				$_SESSION['hasAjax']=true;
				echo '1';
				break; exit;

			case 'fieldChecker': //�������� ���� ������� �� ������������
			$fieldTable=trim(addslashes($_GET['table']));
			$fieldName=trim(addslashes($_GET['field']));
			$fieldValue=addslashes($_GET['value']);
			if (!$fieldValue) $fieldValue=addslashes($_GET[$fieldName]);
			if ($fieldValue && $fieldName && $fieldTable)
			{
				if (trim(checkFldUnique($fieldTable,$fieldName,$fieldValue)))
				{
					print_r('false');
				}
			}
			exit; break;

			default:
				$CTable = new CARXTable("cms_page", "", "filename, title, page_id, parent_page_id,template");
				foreach ($requestedPath as $idx=>$value)
				{

					$value = mysql_escape_string($value);
					$CTable->SetFilter("filename='{$value}' AND parent_page_id='{$parentPageId}'");
					$CTable->Open();
					if ($CTable->GetField('page_id'))
					{

						$i++;
						$this->mPageUrl .= $value . '/';
						$this->mMap[$i] = $CTable->GetRow();
						$this->mMap[$i]['link']=$this->mPageUrl;
						if ($this->mCurrentPageId)
						{
							$this->mPageTitle .= " / ";
						}

						$this->mPageTitle .= $CTable->GetField('title')." ";
						$parentPageId = $CTable->GetField('page_id');
						$this->mCurrentPageId = $CTable->GetField("page_id");
						$this->mCurrentPageFile = $CTable->GetField("filename");
						$this->mCurrentPageTitle = $CTable->GetField("title");
						$this->mPageTemplate=$CTable->GetField('template');

					}


					$CTable->Close();

				}



				$_SESSION['map']=$this->mMap;

				$pageDepth=count($requestedPath);
				if ($pageDepth!=$i)
				{
					$this->ErrorPage("404");
				}
		}


	}

	function handleCoreQuery()
	{
		require_once($_SERVER['DOCUMENT_ROOT']."/cms/config/corequeryAllowed.php");
		header("Content-Type: text/html; charset=windows-1251");
		$extraParams=array();

		$fields=explode(",",$_POST['fields']);
		foreach ($allowQueryFields as $k=>$v)
		{
			if ($allowQueryFields[$k]['table']==trim($_POST['dbtable']) && $allowQueryFields[$k]['action']==$_POST['dbaction'])
			{
				$allOk=true;
				foreach ($fields as $key=>$val)
				{
					if (!in_array($val,$allowQueryFields[$k]['allowedFields']))
					{
						unset($fields[$k]);
					}
					else
					{

						$fieldStr.=$val.",";
					}
				}

			}

		}
		if (!$allOk) return false;


		/*params=array (
		'countField'=>'id',
		'dbaction'=>'select,insert',
		'dbtable'=>'sometable',
		'fields'=>'field1,field2'
		'filter'=>'id>10',
		'order'=>'id DESC'
		'limits'=>0,5
		'onpage=10'//���-�� �������� �� ��������
		) */
		if ($_POST['dbaction']=='select')
		{
			if (is_numeric($_POST['pageSelected']) && is_numeric($_POST['onpage']))
			{
				$rows=$_POST['onpage'];
				if ($_POST['pageSelected']>1)
				{
					$start=($_POST['pageSelected']-1)*$rows;
				}
				else $start=0;
			}
			else
			{
				$start=0;
				$rows=-1;
			}
			$table = new CARXTable(addslashes($_POST['dbtable']),'',substr($fieldStr,0,-1),$start,$rows);
			$table->SetMode(1,0);
			$table->SetFilter($_POST['filter']);
			$table->SetOrder($_POST['order']);
			$data = $table->FetchRows();

			if ($_POST['onpage'])
			{
				$table = new CARXTable(addslashes($_POST['dbtable']),'',"COUNT(*) as total");
				$table->Open();
				$total=$table->GetField('total');
				$table->Close;
				if ($total>0)
				{
					$extraParams['total']=$total;

					for ($i=1; $i<=ceil($total/$_POST['onpage']);$i++)
					{
						$tPages.="$i,";
					}
					$tPages=substr($tPages,0,-1);
					$extraParams['pages']="[$tPages]";

				}

			}

			//print_r(array_to_json_string($data));
			/*echo "{
			name: 'User list',
			list_id: 4,
			table: [
			{id: 1, name: 'Anne', age: 22, mail: 'anne@domain.com'},
			{id: 2, name: 'Amelie', age: 24, mail: 'amelie@domain.com'},
			{id: 3, name: 'Polly', age: 18, mail: 'polly@domain.com'},
			{id: 4, name: 'Alice', age: 26, mail: 'alice@domain.com'},
			{id: 5, name: 'Martha', age: 25, mail: 'martha@domain.com'}
			]
			*/ //}";
			print_r(fetcharray_to_simple_json($data,$extraParams));
		}

		elseif ($_POST['dbaction']=='insert')
		{
			header("Content-Type: text/html; charset=windows-1251");
			$table = new CARXTable($_POST['dbtable']);
			$allowedFld=explode(',',(substr($fieldStr,0,-1)));
			$fields=explode(",",$_POST['fields']);
			for ($i=0;$i<count($fields);$i +=2)
			{
				if (in_array($fields[$i],$allowedFld))
				{
					$table->SetField($fields[$i],htmlspecialchars(addslashes(utf8_win_cms($fields[$i+1]))));
				}
			}
			$table->Insert();

		}



	}

    function getTemplatePlugins($id, $result=null)
    {
            // для ускорения не будем юзать carxtable
            if(!$result) $result=array();
            $tpl=mysql_fetch_assoc(mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."cms__templates WHERE id=$id"));
            $tmp = new CARXTable("cms_plugin2template","template_id={$tpl['id']}");
			$tmp->Open();
			while ($plugin_row = $tmp->GetRow())
			{
                if(!array_key_exists($plugin_row['editable_region'], $result))
                {
                    require_once(CMS_PLUGIN_DIR."/".$plugin_row['plugin'].".lib.php");
                    $result[$plugin_row['editable_region']]=new $plugin_row['plugin'];
                    $result[$plugin_row['editable_region']]->mTemplateId=$tpl['id'];
                    $result[$plugin_row['editable_region']]->mPluginId=$plugin_row['id'];
                    $result[$plugin_row['editable_region']]->mRegion=$plugin_row['editable_region'];
                    $result[$plugin_row['editable_region']]->InitConfig($plugin_row['pluginProperties']);
                    $overLapped[]=$plugin_row['editable_region'];
                }
				$tmp->Next();
			}
			$tmp->Close();
            // наследуем плагины из родительских шаблонов
            $res=mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."cms__templates WHERE id={$tpl['parent_id']}");
            while($row=mysql_fetch_assoc($res))
            {
                 $result=$this->getTemplatePlugins($row['id'], $result);
            }
           return $result;
    }

	function GetCurrentPageUrl()
	{
		return $this->mRU;
	}

	function getHeaders()
	{
		$t=new CARXTable(ARX_DB_TABLE_PREFIX."cms_page", "page_id=".$this->mCurrentPageId);
		$trow=$t->fetchRow();
		$headers=explode('|', $trow['headers']);
		$tpl='';
		if (trim($headers[0]))
		foreach($headers as $id)
		{
			$t1=new CARXTable(ARX_DB_TABLE_PREFIX."cms_js", "id=".$id);
			$row=$t1->FetchRow();
			$tpl.="<!-- ".$row['name']." --> \n";
			$files=unserialize($row['files']);
			if (is_array($files))
			foreach($files as $file)
			{
				if($file['js'])
				{
					$tpl.="\t <script src=\"".$file['js']."\"></script> \n";
				}
				elseif($file['css'])
				{
					$tpl.="\t <link rel=\"stylesheet\" type=\"text/css\" href=\"".$file['css']."\" /> \n";
				}
				else
				{
					$tpl.="\t <!-- ERROR: Cound not include file --> \n";
				}
			}
			$tpl.="<!-- /".$row['name']." --> \n";
		}
		return $tpl;
	}

	//������� ���������� ������ �� ��������, ������� ��������� ������ �� ��������, ������������� �� ��������.
	//���� ������� �������� ����������� $smarty->fetch('path_to_file')
	//������ ����� ��� [editable_region]=>'�������'
	function GetPluginContent($pluginObjects)
	{
		if (is_array($pluginObjects))
		foreach ($pluginObjects as $k=>$v)
		{
			if (!trim($v->mStartFunction))
			{
				$result[$k]=$v->GetOutput();
			}
			else
			{
				$result[$k]=call_user_method($v->mStartFunction,$v);
			}

		}
		return $result;
	}

	function insertAjaxTest($haystack)
	{
		$haystack=str_replace("</title>","</title>
		".AJAX_TEST_FUNCTION,$haystack);
		return $haystack;
	}

	function GeneratePage() //������ ������  GetOutput �� CmsPage
	{
		//echo 'dd';
		if ($this->mPageTemplate)
		{
			//$smarty = new Smarty;
            $pluginContent=$this->GetPluginContent($this->getTemplatePlugins($this->mPageTemplate));
            $tpl_data=mysql_fetch_assoc(mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."cms__templates WHERE id={$this->mPageTemplate}"));
			$pageTpl=file_get_contents(TEMPLATES_DIR."/".$tpl_data['template']);
			if (empty($this->mTitleTagValue))
			{
				$titleTag=PROJECT_NAME." / ".$this->mPageTitle;
			}
			else
			{
				$add=$this->addToDefaultTitle?PROJECT_NAME." / ".$this->mPageTitle." / ":'';
				$titleTag=$add.$this->mTitleTagValue;
			}
			$pageTpl=str_replace(REPLACE_TITLE_AREA,$titleTag,$pageTpl);
			$pageTpl=str_replace(REPLACE_HEADERS_AREA,$this->getHeaders(),$pageTpl);
			$pageTpl=str_replace(array(CURRENT_PAGE_NAME,CURRENT_PAGE_FILE),array($this->mCurrentPageTitle,$this->mCurrentPageFile),$pageTpl);
			if (is_array($pluginContent))
			foreach ($pluginContent as $k=>$v)
			{
				$pageTpl=str_replace('<!-- '.REPLACE_AREA_NAME.' name="'.$k.'" -->',$v,$pageTpl);
			}

			if ($this->requestInfo['words'][0]!='html')
			{
				$pageTpl=$this->handlePage($pageTpl,$this->requestInfo['words'][0]);
			}
			if (!$_SESSION['hasAjax'])
			{
				$pageTpl=$this->insertAjaxTest($pageTpl);
			}

			$this->mBuiltPage=$pageTpl;
			return $pageTpl;
		}

	}

	function handlePage($pageContent,$keyword) //������� ���������� ������� ��� ��������������� ��������� � ����������� �� ��������� �����
	{
		switch ($keyword)
		{
			case 'source': $pageContent=htmlspecialchars($pageContent); break;
			case 'txt':convertHTML2txt($pageContent);
			case 'noimage':cutImagesFromHTML($pageContent);

			default: return $pageContent;
		}
		return $pageContent;
	}

	function getBuiltPage()
	{
		return $this->mBuiltPage;
	}

	function ShowPage()
	{
		echo "{$this->mBuiltPage}";
	}

	function ErrorPage($code)
	{
		switch ($code)
		{
			case 404:
				if (file_exists(ERROR_PAGE_404))
				{
					$errorPage = file_get_contents(ERROR_PAGE_404);
					echo "$errorPage";
				}
				else
				{
					echo 'Страница не найдена';
				}
				break;

			default:
				break;
		}


		exit;
	}


}


?>